package com.app.couponsharelife.ui.main.me.order

import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.OrderClassBean
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.TaobaoOrderBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.listener.MyMultiPurposeListener
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.DataUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.fragment_neworder.*
import kotlinx.android.synthetic.main.neworderfrag_rvitem.view.*
import java.text.DecimalFormat

/**
 *Created by xct on 2019/1/28
 *Description:新的订单列表页面
 */
class NewOrderFragment:LazyFragment() {
    private var animationDrawable:AnimationDrawable?=null
    private var orderClassBean:OrderClassBean?=null
    private var myAdapter:MyAdapter?=null
    val df = DecimalFormat("#0.00")
    private var orderList= arrayListOf<TaobaoOrderBean.RowsBean>()
    private var pageIndex=1
    companion object {
        fun newInstance(orderClassBean: OrderClassBean): NewOrderFragment {
            val fragment = NewOrderFragment()
            val bundle= Bundle()
            bundle.putParcelable("Data",orderClassBean)
            fragment.arguments =bundle
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_neworder

    override fun initViews() {
        orderClassBean=arguments!!.getParcelable("Data")
        setRefresh()
        myAdapter=MyAdapter()
        fragneworder_rv.layoutManager=LinearLayoutManager(activity)
        fragneworder_rv.adapter=myAdapter
    }

    override fun lazyLoad() {
        getGoodsList(false)
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        fragneworder_smart.setOnMultiPurposeListener(object : MyMultiPurposeListener {
            override fun headerReleased() {
                animationDrawable!!.start()
            }

            override fun headerMoving(percent: Float) {
                setAnima(percent)
            }

            override fun headerFinish() {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable!!.stop()
            }

            override fun loadMore() {
                getGoodsList(false)
            }

            override fun refresh() {
                pageIndex=1
                getGoodsList(true)
            }
        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }

    private fun getGoodsList(isRefresh:Boolean){
        if (!isRefresh&&pageIndex==1){
            showProgressDialog("加载中...")
        }
        val map=HashMap<String,String>()
        map["pageNo"]=pageIndex.toString()
        map["pageSize"]="10"
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        map["platform"]=orderClassBean!!.type
        RetrofitWorker.retrofitWorker.getOrderList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<TaobaoOrderBean>>(){
                    override fun onComplete() {

                    }
                    override fun onNext(it: RemoteResultBean<TaobaoOrderBean>) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (it.data!=null&&it.data!!.records.isNotEmpty()){
                            if (pageIndex==1){
                                orderList.clear()
                                if (isRefresh){
                                    fragneworder_llerror.visibility= View.GONE
                                    fragneworder_rv.visibility= View.VISIBLE
                                    fragneworder_smart.finishRefresh()
                                }
                            }else{
                                fragneworder_smart.finishLoadMore()
                            }
                            orderList.addAll(it.data!!.records)
                            if (it.data!!.records.size<10){
                                fragneworder_smart.finishLoadMoreWithNoMoreData()
                            }
                            pageIndex++
                            myAdapter!!.notifyDataSetChanged()
                        }else{
                            if (isRefresh){
                                fragneworder_smart.finishRefresh()
                            }
                            fragneworder_smart.finishLoadMoreWithNoMoreData()
                            if (pageIndex==1&&orderList.size==0){
                                fragneworder_llerror.visibility= View.VISIBLE
                                fragneworder_rv.visibility= View.GONE
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (isRefresh){
                            fragneworder_smart.finishRefresh()
                        }
                        if (pageIndex>1){
                            fragneworder_smart.finishLoadMore()
                        }
                        if (pageIndex==1){
                            fragneworder_smart.finishLoadMoreWithNoMoreData()
                            fragneworder_llerror.visibility= View.VISIBLE
                            fragneworder_rv.visibility= View.GONE
                        }
                        if (e is OtherException){
                            //showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                            //Log.e("eeee","----->"+e.toString())
                        }
                    }

                })
    }
    inner class MyAdapter:RecyclerView.Adapter<MyHolder>(){
        val commissionRatio=DataUtils().getCommissionRatio()
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
            val view=LayoutInflater.from(parent.context).inflate(R.layout.neworderfrag_rvitem,parent,false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return orderList.size
        }

        override fun onBindViewHolder(holder: MyHolder, position: Int) {
            if (orderList.isNotEmpty()){
                val rowsBean=orderList[position]
                Glide.with(holder.itemView.context)
                        .asBitmap()
                        .apply(RequestOptions().error(R.drawable.ic_app_place_holder3))
                        .load(rowsBean.itemurl)
                        .into(holder.order_imag)
                holder.order_title.text="      "+rowsBean.title
                holder.order_type.setImageResource(when(rowsBean.platform){
                    1->R.drawable.goods_tb
                    2->R.drawable.goods_pdd
                    3->R.drawable.goods_jd
                    else->R.drawable.goods_tb
                })
                val type=rowsBean.type?:"2"
                val ygPrice=(rowsBean.estimatecome?:"0.0").toDouble()
                if ("1"==type){
                    val price=df.format((rowsBean.zeroPrice?:"0.0").toDouble())
                    holder.order_yhprice.text="预估补贴￥$price"
                }else{
                    val price=df.format(ygPrice*commissionRatio.toDouble())
                    holder.order_yhprice.text="预估奖励￥$price"
                }
                holder.tvorder_number.text="订单号   "+rowsBean.ordersn
                holder.order_time.text="创建时间："+rowsBean.createTime
                holder.order_price.text=rowsBean.price+"元"
                var orderType=""
                when(rowsBean.orderstatus){
                    "0"->{
                       orderType="已失效"
                    }
                    "1"->{
                        orderType="待结算"
                    }
                    "2"->{
                        orderType="已结算"
                    }
                    else->{
                        orderType="待结算"
                    }
                }
                if ("0"==rowsBean.orderstatus||ygPrice<=0){
                    holder.order_yhprice.visibility=View.INVISIBLE
                    holder.tvContent.visibility=View.INVISIBLE
                    holder.order_price.visibility=View.INVISIBLE
                }else{
                    holder.order_yhprice.visibility=View.VISIBLE
                    if (3!=rowsBean.platform){
                        holder.tvContent.visibility=View.VISIBLE
                        holder.order_price.visibility=View.VISIBLE
                    }else{
                        holder.tvContent.visibility=View.INVISIBLE
                        holder.order_price.visibility=View.INVISIBLE
                    }
                }
                holder.orderType.text=orderType
            }
        }
    }
    inner class MyHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var tvorder_number:TextView=itemview.neworderfrag_rvitem_ddh
        var order_imag:ImageView=itemview.neworderfrag_rvitem_goodsimg
        var order_type:ImageView=itemview.neworderfrag_rvitem_imgtype
        var order_title:TextView=itemview.neworderfrag_rvitem_title
        var order_time:TextView=itemview.neworderfrag_rvitem_ordertime
        var order_price:TextView=itemview.neworderfrag_rvitem_orderprice
        var order_yhprice:TextView=itemview.neworderfrag_rvitem_yhprice
        var orderType:TextView=itemview.neworderfrag_rvitem_ddtype
        var tvContent:TextView=itemview.tvxfje
    }
}